package cn.edu.zut.dao;

import cn.edu.zut.model.BookType;
import cn.edu.zut.model.Reader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import sun.security.action.GetBooleanAction;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository()
public class BookTypeDaoImpl implements BookTypeDao {

    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    BookType bookType;

    @Autowired
    List<BookType> bookTypeList;

    public int insertBookType(BookType bookType) {

        String INSERT_BOOKTYPE="INSERT INTO booktype(id,typename) VALUES(?,?)";
        Object[] args={bookType.getId(),bookType.getTypename()};
        int result=jdbcTemplate.update(INSERT_BOOKTYPE,args);
        return result;
    }

    public int deleteBookType(BookType bookType) {
        String DELETE_BOOKTYPE="DELETE  FROM booktype where id=?";
        Object[] args={bookType.getId()};
        int result=jdbcTemplate.update(DELETE_BOOKTYPE,args);
        return result;
    }

    public int updateBookType(BookType bookType) {
        String UPDATE_BOOKTYPE="UPDATE booktype set typename=? where id=?";
        Object[] args={bookType.getTypename(),bookType.getId()};
        int result=jdbcTemplate.update(UPDATE_BOOKTYPE,args);
        return result;
    }

    public List<BookType> select_All_BookType() {

        String SELECT_ALL_BOOKTYPE="SELECT * FROM booktype";
        RowMapper<BookType> readerRowMapper=new BeanPropertyRowMapper<BookType>(BookType.class);
        bookTypeList=jdbcTemplate.query(SELECT_ALL_BOOKTYPE,readerRowMapper);
        return bookTypeList;
    }

    //通过类型名查询到id
    public int selectIdByTypeName(String typename) {
        String SELECT_ID = "SELECT * FROM booktype WHERE typename=?";
        Object[] args = {typename};
        RowMapper<BookType> rowMapper = new RowMapper<BookType>() {
            public BookType mapRow(ResultSet resultSet, int i) throws SQLException {
                BookType bookType = new BookType();
                bookType.setId(resultSet.getInt("id"));
                bookType.setTypename(resultSet.getString("typename"));
                return bookType;
            }
        };
        bookType=jdbcTemplate.queryForObject(SELECT_ID,rowMapper,args);
        return bookType.getId();
    }











}
